package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.service.CourseTeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author hand4j
 * @version 1.0
 * @description 师资管理业务接口实现类
 * @date 2023/3/14 19:21
 */
@Slf4j
@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {
    @Autowired
    CourseTeacherMapper courseTeacherMapper;

    @Override
    public List<CourseTeacher> queryCourseTeacherList(Long courseId) {
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId, courseId);
        List<CourseTeacher> courseTeachers = courseTeacherMapper.selectList(queryWrapper);
        return courseTeachers;
    }

    @Transactional
    @Override
    public CourseTeacher saveCourseTeacher(CourseTeacher courseTeacher) {
        Long id = courseTeacher.getId();

        if(id != null){
            CourseTeacher courseTeacherOld = courseTeacherMapper.selectById(id);
            BeanUtils.copyProperties(courseTeacher, courseTeacherOld);
            int update = courseTeacherMapper.updateById(courseTeacherOld);
            if(update <= 0){
                XueChengPlusException.cast("修改师资信息失败");
            }
        } else {
            int insert = courseTeacherMapper.insert(courseTeacher);
            if(insert <= 0){
                XueChengPlusException.cast("添加师资信息失败");
            }
            id = courseTeacher.getId();
        }
        return courseTeacherMapper.selectById(id);
    }


    @Transactional
    @Override
    public void deleteCourseTeacher(Long courseId, Long id) {
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId, courseId);
        queryWrapper.eq(CourseTeacher::getId, id);
        int delete = courseTeacherMapper.delete(queryWrapper);
        if(delete <= 0){
            XueChengPlusException.cast("删除师资信息失败");
        }
    }

    @Override
    public void deleteCourseTeacherByCourseId(Long courseId) {
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId, courseId);
        courseTeacherMapper.delete(queryWrapper);
    }
}
